<template>
  <div class="box contenBox">
    <div class="divForm">
      <el-form
        :model="formData"
        :rules="rules"
        ref="ruleForm"
        class="demo-ruleForm"
      >
        <el-row :gutter="30">
          <el-col :span="6">
            <el-form-item
              label="货品编码"
              prop="code"
            >
              <el-input
                v-model="formData.code"
                placeholder="请输入"
                clearable
                disabled="disabled"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              label="货品类型"
              prop="goodsTypeName"
              class="selectIcon"
            >
              <el-autocomplete
                v-model="formData.goodsTypeName"
                :fetch-suggestions="querySearchAsync"
                placeholder="请输入内容"
                suffix-icon="el-icon-search"
                :trigger-on-focus="false"
                clearable
                @select="handleSelect"
                @change="handleOwnertypeChange"
              ></el-autocomplete>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              label="货品名称"
              prop="name"
            >
              <el-input
                v-model="formData.name"
                placeholder="请输入"
                maxlength="10"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              label="货品条码"
              prop="barCode"
            >
              <el-input
                v-model="formData.barCode"
                placeholder="请输入"
                maxlength="20"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="30">
          <el-col :span="6">
            <el-form-item
              label="货主"
              prop="ownerName"
              class="selectIcon"
            >
              <el-autocomplete
                v-model="formData.ownerName"
                :fetch-suggestions="querySearchOwner"
                placeholder="请输入内容"
                suffix-icon="el-icon-search"
                :trigger-on-focus="false"
                clearable
                @select="handleSelectOwner"
                @change="hancleChange"
              ></el-autocomplete>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              label="质检方式"
              prop="inspectionType"
            >
              <el-select
                v-model="formData.inspectionType"
                placeholder="请选择"
                style="width: 100%"
                clearable
              >
                <el-option
                  v-for="item in useTypeData"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              label="温度要求"
              prop="temperatureType"
            >
              <el-select
                v-model="formData.temperatureType"
                placeholder="请选择"
                style="width: 100%"
                clearable
              >
                <el-option
                  v-for="item in temperatureTypeData"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              label="承重要求"
              prop="bearingType"
            >
              <el-select
                v-model="formData.bearingType"
                placeholder="请选择"
                style="width: 100%"
                clearable
              >
                <el-option
                  v-for="item in bearingTypeData"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="30">
          <el-col :span="6">
            <el-form-item
              label="体积"
              prop="volume"
              class="formInfoTip"
            >
              <el-input
                v-model="formData.volume"
                placeholder="请输入"
                type="number"
                maxlength="10"
                clearable
                @change="handleBlurVolume"
              ><span slot="append">m³</span></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              label="指定库区"
              prop="areaId"
            >
              <el-select
                v-model="formData.areaId"
                placeholder="请选择"
                style="width: 100%"
                clearable
              >
                <el-option
                  v-for="item in areaData"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              label="单价"
              class="formInfoTip"
            >
              <el-input
                v-model="formData.price"
                placeholder="请输入"
                maxlength="10"
                clearable
                type="number"
                @change="handleBlur"
              ><span slot="append">元</span></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="单位">
              <el-input
                v-model="formData.unit"
                placeholder="请输入"
                maxlength="50"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="30">
          <el-col :span="6">
            <el-form-item
              label="保质天数"
              class="formInfoTip"
            >
              <el-input
                v-model="formData.guaranteeDay"
                placeholder="请输入"
                clearable
                maxlength="10"
                :precision="0"
                @change="handleBlurDay"
              ><span slot="append">天</span></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="buttonBox">
      <base-button
        class="unimportanceButton btnReturn"
        @click="btnReturn"
      >返回</base-button>
      <base-button
        class="minorImportantButton btnSave"
        @click="handleSubmit"
      >提交</base-button>
    </div>
  </div>
</template>
<script lang="ts">
import { Component } from 'vue-property-decorator'
import { mixins } from 'vue-class-component'
import { ElForm } from 'element-ui/types/form'
import {
  // validateNumber,
  isIntegerNotMust,
  validateValidity
  // validateValiditys
} from '@/utils/validate'
// 关闭窗口
import SinglePage from '@/mixin/single-page'
// 公用组件
// 按钮
import BaseButton from '@/components/base-button/index.vue'
// 基本数据
import {
  temperatureTypeOptions, // CW
  bearingTypeOptions, // CZ
  inspectionTypeOptions // YT
} from '@/utils/common-select-data'
// interface接口
import {
  ICommonReturn,
  ICommonSelectOptionsString
} from '@/utils/common-interface'
import { IOwnerTableData } from '@/module-business/interface/owner'
// api数据接口
import { generateWarehouseCode } from '@/api/common-api'
import {
  addGoods,
  updateGoods,
  getGoodsListDetails,
  getGoodsTypeList,
  getGoodsOwnerTypeList
} from '@/module-base/api/goods'
import { getAllAreaList } from '@/module-base/api/area'
@Component({
  name: 'AreaAdd',
  components: {
    BaseButton
  }
})
export default class extends mixins(SinglePage) {
  private formData = {
    code: '',
    goodsTypeId: '',
    goodsTypeName: '', // 货主名称
    name: '',
    ownerId: '',
    ownerName: '', // 货主名称
    temperatureType: '',
    inspectionType: '',
    bearingType: '',
    volume: '',
    areaId: '',
    barCode: '',
    price: '',
    unit: '',
    guaranteeDay: ''
  } as any

  private temperatureTypeData: ICommonSelectOptionsString[] = [] // 常温类型
  private bearingTypeData: ICommonSelectOptionsString[] = [] // 承重类型
  private useTypeData: ICommonSelectOptionsString[] = [] // 用途类型
  private warehouseData = []
  private options = []
  private value = []
  private typelist: IOwnerTableData[] = []
  private ownerTypelist: IOwnerTableData[] = []
  private areaData = []
  private loading = false
  private state = ''
  private timeout = null as any
  private timeID?: number = undefined

  // 校验表单
  private rules = {
    code: [{ required: true, message: '请输入编码', trigger: 'blur' }],
    goodsTypeName: [
      {
        required: true,
        message: '请输入货品类型名称/货品类型编码',
        trigger: 'change'
      }
    ],
    name: [{ required: true, message: '请输入货品名称', trigger: 'blur' }],
    barCode: [{ required: true, message: '请输入货品条码', trigger: 'blur' }],
    ownerName: [
      { required: true, message: '请输入货主名称/编码', trigger: 'change' }
    ],
    inspectionType: [
      { required: true, message: '请选择质检类型', trigger: 'change' }
    ],
    temperatureType: [
      { required: true, message: '请选择温度类型', trigger: 'change' }
    ],
    bearingType: [
      { required: true, message: '请选择承重类型', trigger: 'change' }
    ],
    volume: [
      {
        required: true,
        message: '请输入数字',
        trigger: 'blur'
      }
    ]
    // volume: [{ required: true, validator: validateNumber, trigger: 'blur' }]
  }

  mounted() {
    this.initData()
  }

  // 功能
  // 获取select数据
  private async initData() {
    this.temperatureTypeData = temperatureTypeOptions
    this.bearingTypeData = bearingTypeOptions
    this.useTypeData = inspectionTypeOptions
    const id = this.$route.params.id
    if (id === 'null') {
      // 新增
      Promise.all([
        getGoodsTypeList({ params: '' }),
        getGoodsOwnerTypeList({ params: '' }),
        generateWarehouseCode('HP')
      ]).then(res => {
        this.typelist = res[0].data
        this.ownerTypelist = res[1].data
        this.formData.code = res[2].data
      })
    } else {
      // 编辑
      Promise.all([
        getGoodsTypeList({ params: '' }),
        getGoodsOwnerTypeList({ params: '' }),
        getGoodsListDetails(id)
      ]).then(res => {
        this.typelist = res[0].data
        this.ownerTypelist = res[1].data
        const data = res[2].data
        const goodsTypeName = this.typelist.filter(
          (item: any) => item.id === data.goodsTypeId
        )[0].name
        const ownerName = this.ownerTypelist.filter(
          (item: any) => item.id === data.ownerId
        )[0].name
        this.formData = {
          ...data,
          goodsTypeName,
          ownerName
        }
        this.getAreaData(this.formData.ownerId)
      })
    }
  }

  // 制定库区
  private async getAreaData(id: any) {
    const { data } = await getAllAreaList({ ownerId: id })
    this.areaData = data
  }

  // 提交数据
  private handleSubmit() {
    (this.$refs.ruleForm as ElForm).validate(async(valid: boolean) => {
      if (valid) {
        const form = this.formData
        const params = {
          ...form
        }
        let data: ICommonReturn
        if (this.$route.params.id === 'null') {
          // 新增操作
          data = ((await addGoods(params)) as unknown) as ICommonReturn
        } else {
          // 编辑
          data = ((await updateGoods(params)) as unknown) as ICommonReturn
        }
        if (data.code === 0) {
          this.$message({
            showClose: true,
            message: '恭喜你，提交成功！',
            type: 'success'
          })
          this.closeWindow()
        } else {
          this.$message({
            showClose: true,
            message: data.msg,
            type: 'error'
          })
        }
      } else {
        return false
      }
    })
  }

  // ui
  handleBlurVolume(newVal: any) {
    const eror = this.$message
    this.formData.volume = validateValidity(newVal, eror)
  }

  // 验证价格
  handleBlur(newVal: any) {
    const error = this.$message
    this.formData.price = validateValidity(newVal, error)
  }

  // 验证天数是否整数
  handleBlurDay(val: any) {
    if (!isIntegerNotMust(val)) {
      // this.formData.guaranteeDay = ''
      this.$message.error('请输入正确的整数')
      return false
    }
  }

  // 返回
  btnReturn() {
    this.closeWindow()
  }

  // 货品类型
  querySearchAsync(queryString: any, cb: any) {
    var restaurants = this.typelist
    var results = queryString
      ? restaurants.filter(this.createStateFilter(queryString))
      : restaurants
    clearTimeout(this.timeID)
    this.timeID = window.setTimeout(() => {
      cb(
        results.map((item: IOwnerTableData) => {
          return {
            value: item.name,
            id: item.id
          }
        })
      )
    }, 1000 * Math.random())
  }

  // 获取货主类型id
  handleSelect(item: any) {
    this.formData.goodsTypeId = item.id
  }

  // 货主
  querySearchOwner(queryString: any, cb: any) {
    var restaurants = this.ownerTypelist
    var results = queryString
      ? restaurants.filter(this.createStateFilter(queryString))
      : restaurants
    clearTimeout(this.timeID)
    this.timeID = window.setTimeout(() => {
      cb(
        results.map((item: IOwnerTableData) => {
          return {
            value: item.name,
            id: item.id
          }
        })
      )
    }, 1000 * Math.random())
  }

  // 获取货主id
  handleSelectOwner(item: any) {
    this.formData.ownerId = item.id
    this.getAreaData(item.id)
  }

  private handleOwnertypeChange(newValue: string) {
    if (!newValue) {
      this.formData.goodsTypeId = ''
    }
    if (!this.formData.goodsTypeId) {
      this.formData.goodsTypeName = ''
    }
  }

  hancleChange(newValue: string) {
    if (!newValue) {
      this.formData.ownerId = ''
    }
    if (!this.formData.ownerId) {
      this.formData.ownerName = ''
    }
  }

  createStateFilter(queryString: any) {
    return (state: IOwnerTableData) => {
      return (
        (state.name as any).toLowerCase().indexOf(queryString.toLowerCase()) >
        -1 || (state.code as any).toLowerCase().indexOf(queryString.toLowerCase()) >
        -1
      )
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
<style lang="scss">
</style>
